package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Week9homework extends ListActivity implements Runnable {
    private static final String TAG = "Week9homework";
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] list_data={"one","two","three","测试数据"};
        ListAdapter adapter=new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,list_data);
        setListAdapter(adapter);
        handler=new Handler(){
            public void handleMessage(Message msg){
                if(msg.what==5){
                    List<String> list2=(List<String>) msg.obj;
                    ListAdapter adapter=new ArrayAdapter<String>(Week9homework.this, android.R.layout.simple_expandable_list_item_1,list2);
                    setListAdapter(adapter);
                }
                super.handleMessage(msg);
            }
        };
        Thread t=new Thread(this);//开启子线程
        t.start();//调用的是MyTask的run()方法
    }

    @Override
    public void run() {
        Log.i(TAG, "run:  Running......");
        try {
            Thread.sleep(3000);
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
        List<String> retList=new ArrayList<>();
        try {
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            String title=doc.title();
            Log.i(TAG, "run: title"+title);
            Elements tables=doc.getElementsByTag("table");
            Element table=tables.get(1);
            Elements trs=table.getElementsByTag("tr");
            for(int i=1;i<trs.size();i++){
                if(trs.get(i).getElementsByTag("td").size()>0){
                    Elements tds=trs.get(i).getElementsByTag("td");
                    for(int j=0;j<tds.size();j+=8){
                        Element td1=tds.get(j);
                        Element td2=tds.get(j+4);
                        String td3=td1.text();
                        String td4=td2.text();
                        Log.i(TAG, "run: "+td3+"==>"+td4);
                        retList.add(td3+"==>"+td4);
                        }
                    }
                }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Message msg=handler.obtainMessage(5);
        msg.obj=retList;
        handler.sendMessage(msg);
    }
}